import { Component, Vue, Watch } from 'vue-property-decorator'
import { Action } from 'vuex-class'
import styles from './OrderConfirm.less'
import { Route } from 'vue-router'
const QRCode = require('qrcode')
Component.registerHooks(['beforeRouteLeave'])
// import AlipaySvg from '@/assets/alipay-logo.svg'//import在ie下有问题，待修复

const amountList: any[] = [
  { label: '电子印章服务费', key: 1, tips: '含证书' },
  { label: '硬件介质费用', key: 2 },
  { label: '加密机硬件费', key: 3 },
  { label: '快递费', key: 4 },
]

const resultMap: any = {
  1: '', // 待支付
  2: 'success', // 待发货
  3: 'success', // 待收货
  4: 'success', // 确认收货
  5: '', // 支付中
  96: 'timeout', // 过期
  97: 'fail', // 异常终止
  98: 'timeout', // 超时取消
  99: 'close', // 订单关闭（用户取消）
}

@Component({})
export default class OrderConfirm extends Vue {
  private payType = 1
  private type = 1 // 付费方式
  private payForm = ''
  private orderId: any = null
  private sealApplyId: any = null
  private orderInfo: any = {}
  private goods: any[] = []
  private timer: any = null
  private qrTimer: any = null
  private visible: boolean = false
  private clickSecond: number = 30
  private qrSecond: number = 50
  private qrCodeImg: string = ''
  private loading: boolean = false
  private payStatus: any = null
  private receiveContent: string = ''
  private payAmount: string = ''

  @Action('paymentOrder/queryPayOrderCreatedInfo')
  private queryPayOrderCreatedInfo!: any
  @Action('paymentOrder/confirmPayOrder') private confirmPayOrder!: any
  @Action('paymentOrder/queryPayOrderStatus') private queryPayOrderStatus!: any
  @Action('paymentOrder/cancelPayOrder') private cancelPayOrder!: any

  protected render(h: any) {
    return (
      <div class={styles.container}>
        <div class={styles.content}>
          <div class={styles.form}>
            {this.payType === 1 && (
              <p class={styles.payType}>
                支付方式：
                <el-radio
                  v-model={this.type}
                  label={1}
                  style="vertical-align: text-top;"
                >
                  支付宝
                  <img src={require('@/assets/alipay-logo.svg')} />
                  <p class={styles.payTypeInfo}>
                    <i class="el-icon-warning" />
                    公务卡用户请使用支付宝绑定公务卡后完成扫码支付
                  </p>
                </el-radio>
              </p>
            )}
            {this.payType === 2 && (
              <p class={styles.payType}>
                <p class={styles.row}>
                  <span class={styles.title}>付费方式：</span>统一支付
                </p>
                <p class={styles.row}>
                  <p class={styles.col}>
                    <span class={styles.title}>统一付费方：</span>
                    {this.orderInfo.payOrganizeName}
                  </p>
                  <p class={styles.col}>
                    <span class={styles.title}>付费方管理员：</span>
                    {this.orderInfo.payingAdministrator}
                  </p>
                </p>
              </p>
            )}
            <h3 class={styles.label}>
              应付金额&nbsp;<span class={styles.part}>总费用</span>
            </h3>
            <p class={styles.amount}>
              ￥{this.orderInfo.payAmount}
              <span class={styles.part}>
                （
                {this.goods &&
                  this.goods.map((good: any, index: number) => {
                    return (
                      <span>
                        {index !== 0 && <span>&nbsp;+&nbsp;</span>}￥
                        {(good.price / good.quantity).toFixed(2)}
                        {good.name}&nbsp;x{good.quantity}&nbsp;{good.tips}
                      </span>
                    )
                  })}
                ）
              </span>
            </p>
          </div>
          {(this.payStatus === 1 || this.payStatus === 5) && (
            <el-button
              class="bg-color-blue"
              type="primary"
              disabled={this.loading}
              onClick={this.confirmPay}
            >
              确认支付
            </el-button>
          )}
          {(this.payStatus === 1 || this.payStatus === 5) && (
            <el-button
              class="btn-height-32"
              disabled={this.loading}
              onClick={this.toModifyApply}
            >
              修改订单
            </el-button>
          )}
        </div>
        {/* <div v-append={this.payForm}></div> */}
        <el-dialog
          custom-class="confirm-pay-dialog"
          width={'569px'}
          visible={this.visible}
          show-close={false}
          modal-append-to-body={false}
          append-to-body
        >
          <p slot="title">
            扫码支付
            <el-tooltip placement="bottom-start">
              <p slot="content">
                请确认收款方信息为：
                {(this.receiveContent || '').replace('收款方：', '')}
              </p>
              <i class="el-icon-question ml10" />
            </el-tooltip>
          </p>
          <div class={styles.payInfo}>
            {/* <p>
              <span></span>{this.receiveContent}
						</p>
            <p>交易金额：{this.payAmount}</p> */}
            <div class={styles.info}>
              <p>
                收款方：{(this.receiveContent || '').replace('收款方：', '')}
              </p>
              <p>
                应付金额：
                <span class="red f26">
                  ￥{(this.payAmount || '').replace('元', '')}
                </span>
              </p>
            </div>
            <div class={styles.qrCodeWrapper}>
              <p class={styles.logo}>
                <img
                  src={require('@/assets/alipay-logo.png')}
                  alt="logo"
                  width="70px"
                  height="25px"
                />
              </p>
              <div class={styles.qrPayImg}>
                <img src={this.qrCodeImg} width="101px" height="auto" />
              </div>
              <div class={styles.explain}>
                <div>
                  打开手机支付宝
                  <br />
                  扫一扫继续付款
                </div>
              </div>
            </div>
            {/* <div class={styles.example}>
							<img src={require("@/assets/scanpay.jpeg")} alt="扫一扫" />
						</div> */}
          </div>
          <p class={styles.tips}>
            <i class="el-icon-warning" />
            付款完成前请不要关闭此窗口，
            {this.clickSecond ? (
              <span class="fw-bold">{this.clickSecond}s&nbsp;</span>
            ) : (
              <span>完成付款</span>
            )}
            后请根据您的情况点击下面的按钮
          </p>

          <p slot="footer">
            <el-button
              type="default"
              disabled={!!this.clickSecond}
              onClick={() => this.problemOrFinish('fail')}
            >
              付款遇到问题
            </el-button>
            <el-button
              type="primary"
              disabled={!!this.clickSecond}
              onClick={() => this.problemOrFinish('success')}
            >
              已完成付款
            </el-button>
          </p>
        </el-dialog>
      </div>
    )
  }

  @Watch('visible')
  private visibleWatch(val: boolean) {
    if (val) {
      this.clickSecond = 30
      this.countDown(this.clickSecond, (time: number) => {
        this.clickSecond = time
      })
    }
  }

  private mounted() {
    this.orderId = this.$route.query.orderId || ''
    this.sealApplyId = this.$route.query.sealApplyId || ''
    this.queryOrderInfo()
  }
  private queryOrderInfo() {
    this.queryPayOrderCreatedInfo({ payOrderId: this.orderId }).then(
      (res: any) => {
        this.payType = res.payType
        this.orderInfo = res || {}
        this.goods =
          (res.goods || [])
            .map((good: any) => {
              const amount =
                amountList.find(amount => amount.key === good.goodsType) ||
                {} ||
                ''

              return {
                ...good,
                name: amount.label,
                tips: amount.tips,
              }
            })
            .filter((good: any) => good.goodsType !== 3) || []
        this.payStatus = res.status
        if (!!resultMap[res.status]) {
          // 如果订单状态不是支付中或待支付，将跳转其他页面
          // if (resultMap[res.status] === "timeout") {
          // 	this.$router.replace({
          // 		name: "paymentOrder",
          // 		params: { type: "newApply" },
          // 		query: { sealApplyId: this.sealApplyId }
          // 	});
          // } else {
          if (resultMap[res.status] === 'success' && this.payStatus === 2) {
            this.$router.push({
              name: 'payResult',
              params: { type: 'submit' },
              query: {
                orderId: this.orderId,
                sealApplyId: this.sealApplyId,
                payType: this.payType.toString(),
              },
            })
          } else {
            this.$router.push({
              name: 'payResult',
              params: { type: resultMap[res.status] },
              query: {
                orderId: this.orderId,
                sealApplyId: this.sealApplyId,
                payType: this.payType.toString(),
              },
            })
          }
          // }
        }
      }
    )
  }

  private makeQrcode(url: string) {
    QRCode.toDataURL(
      url,
      {
        errorCorrectionLevel: 'H',
      },
      (err: any, url: string) => {
        this.qrCodeImg = url
      }
    )
  }

  private toOrderPage() {
    this.$router.replace({
      name: 'applyPage',
      params: { type: 'newApply' },
      query: { id: this.sealApplyId, ic: 'true', orderId: this.orderId },
    })
  }
  // 返回修改
  private async toModifyApply() {
    this.loading = true
    this.cancelPayOrder(this.orderId)
      .then((res: any) => {
        this.$message.success('取消订单成功')
        this.loading = false
        this.toOrderPage()
      })
      .catch(() => {
        this.loading = false
      })
  }

  private async confirmPay() {
    try {
      const res: any = await this.confirmPayRequest()
      if (!res) return
      if (this.payType === 2) {
        this.$router.push({
          name: 'payResult',
          params: { type: 'submit' },
          query: {
            orderId: this.orderId,
            sealApplyId: this.sealApplyId,
            payType: this.payType.toString(),
            needAudit: res.isAutomaticPayment === 0 ? 'true' : undefined, // 是否需要统付方审核
          },
        })
      } else {
        this.visible = true
      }
    } catch (e) {
      console.log(e)
    }
  }

  private async confirmPayRequest() {
    // 获取二维码或刷新二维码
    this.loading = true

    return new Promise((resolve, reject) => {
      this.confirmPayOrder({ payOrderId: parseInt(this.orderId) })
        .then((res: any) => {
          this.loading = false
          if (this.payType === 1) {
            // this.makeQrcode(res.qrCode)
            this.qrCodeImg = `data:image/png;base64,${res.qrImgBase64}`
            this.payAmount = res.payAmount
            this.receiveContent = res.receiveContent
            this.qrSecond = 50
            this.countDownForQrCode(
              this.qrSecond,
              (time: number) => {
                this.qrSecond = time
                if (time % 3 === 0) {
                  // 轮询设置3秒
                  this.queryOrderStatus()
                    .then((res: any) => {
                      // 轮询结果
                      if (!!resultMap[res.status]) {
                        // 跳结果页
                        this.jumpToResult(resultMap[res.status])
                      }
                    })
                    .catch((e: any) => {
                      this.jumpToResult('fail')
                    })
                }
              },
              () => {
                this.confirmPayRequest()
              }
            )
          }
          resolve(res)
        })
        .catch((e: any) => {
          console.log(e)
          if (e.errorCode && e.errorCode === 'PAY_ORDER_CANCEL') {
            setTimeout(() => {
              this.toOrderPage()
            }, 3000)
          }
          this.loading = false
          reject(e)
        })
    })
  }

  private jumpToResult(status: string) {
    this.qrTimer && clearInterval(this.qrTimer)
    this.timer && clearInterval(this.timer)
    this.$router.push({
      name: 'payResult',
      params: { type: status },
      query: {
        orderId: this.orderId,
        sealApplyId: this.sealApplyId,
        payType: this.payType.toString(),
      },
    })
  }

  private async queryOrderStatus() {
    return await this.queryPayOrderStatus({ payOrderId: this.orderId })
  }

  private beforeRouteLeave(to: Route, from: Route, next: any) {
    this.qrTimer && clearInterval(this.qrTimer)
    this.timer && clearInterval(this.timer)
    next()
  }

  private problemOrFinish(status: any) {
    // const
    this.qrTimer && clearInterval(this.qrTimer)
    this.timer && clearInterval(this.timer)
    this.queryOrderStatus()
      .then((res: any) => {
        // 轮询结果
        if (!!resultMap[res.status]) {
          // 跳结果页
          this.jumpToResult(resultMap[res.status])
        } else {
          this.jumpToResult('fail')
        }
      })
      .catch((e: any) => {
        this.jumpToResult('fail')
      })
  }

  private countDown(time: number, step?: any, cb?: any) {
    if (step) step(time)
    this.timer && clearInterval(this.timer)
    this.timer = setInterval(() => {
      if (time <= 0) {
        this.timer && clearInterval(this.timer)
        if (cb) cb()

        return
      }

      // eslint-disable-next-line no-param-reassign
      time--
      if (step) step(time)
    }, 1000)
  }

  private countDownForQrCode(time: number, step?: any, cb?: any) {
    if (step) step(time)
    this.qrTimer && clearInterval(this.qrTimer)
    this.qrTimer = setInterval(() => {
      if (time <= 0) {
        this.qrTimer && clearInterval(this.qrTimer)
        if (cb) cb()

        return
      }

      // eslint-disable-next-line no-param-reassign
      time--
      if (step) step(time)
    }, 1000)
  }
}
